/* 
 * Copyright (c) 2006-2014, Ivan Jeukens
 * All rights reserved.
 *
 * This software is open-source under GNU General Public License, version 2 
 * see LICENSE file
 */
package odog.ruleChecker;

import odog.codegen.util.FileGenerator;
import odog.codegen.util.FileGeneratorParser;
import odog.codegen.util.FileGenerator;
import odog.codegen.util.FileGeneratorParser;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.LinkedList;
import javax.swing.DefaultListModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

/**
 *
 * @author  ivan
 */
public class CheckerResultsFrame extends javax.swing.JFrame {
    
    /** Creates new form CheckerResultsFrame */
    public CheckerResultsFrame() {
        initComponents();
        
        currentSelectedRule = null;
        
        setRuleText("");
        setRuleSyntaxTree(new DefaultMutableTreeNode());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        componentXML = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        componentSyntax = new javax.swing.JTree();
        jScrollPane3 = new javax.swing.JScrollPane();
        ruleList = new javax.swing.JList();
        jScrollPane4 = new javax.swing.JScrollPane();
        ruleText = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        ruleSyntaxTree = new javax.swing.JTree();
        jLabel5 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        testPathField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Checker Results");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 0, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 666, Short.MAX_VALUE)
        );

        componentXML.setColumns(20);
        componentXML.setEditable(false);
        componentXML.setRows(5);
        jScrollPane1.setViewportView(componentXML);

        jScrollPane2.setViewportView(componentSyntax);

        ruleList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        ruleList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        ruleList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                ruleListMouseReleased(evt);
            }
        });
        jScrollPane3.setViewportView(ruleList);

        ruleText.setColumns(20);
        ruleText.setEditable(false);
        ruleText.setRows(5);
        jScrollPane4.setViewportView(ruleText);

        jLabel1.setText("Component XML");

        jLabel2.setText("Component syntax tree");

        jButton1.setText("Syntax Test");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("Checked Rules");

        jLabel4.setText("Rule");

        jScrollPane5.setViewportView(ruleSyntaxTree);

        jLabel5.setText("Rule syntax tree");

        jButton2.setText("Rule Test");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Graph test");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        testPathField.setText("/home/ivan/odog/tests/regression");

        jLabel6.setText("Test Path");

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                            .add(jLabel1)
                            .add(layout.createSequentialGroup()
                                .add(jLabel2)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jButton1)
                                .add(25, 25, 25)
                                .add(jButton3)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jLabel3)
                            .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 151, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                    .add(layout.createSequentialGroup()
                        .add(jLabel6)
                        .add(25, 25, 25)
                        .add(testPathField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel4))
                    .add(layout.createSequentialGroup()
                        .add(12, 12, 12)
                        .add(jLabel5)
                        .add(37, 37, 37)
                        .add(jButton2))
                    .add(jScrollPane5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 507, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 507, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jLabel3)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jButton2)
                            .add(jLabel5))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE)
                                .add(16, 16, 16)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                                    .add(jLabel2)
                                    .add(jButton3)
                                    .add(jButton1))
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(jScrollPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 244, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jLabel6)
                            .add(testPathField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 26, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    // Referente ao botao de geracao de teste para a regra
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String testPath = testPathField.getText();

        String goldenSyntaxFile = new String(componentName + "_" + 
                currentSelectedRule.toString());
        try {
            File f = new File(testPath + goldenSyntaxFile);
            FileOutputStream fos = new FileOutputStream(f);
            PrintStream ps = new PrintStream(fos);

            ps.print(currentSelectedRule.exportRule());

            fos.close();
        }
        catch(Exception ex) {
            System.out.println(ex);
        }
        
        FileGenerator generator = 
                FileGeneratorParser.parse("/home/ivan/odog/odog/src/odog/test/TestRule.xml");
        if(isAtomic) {
            generator.setArgumentValue("isAtomic", "true");
        }
        else {
            generator.setArgumentValue("isAtomic", "false");
        }
        generator.setArgumentValue("compName", componentName);
        generator.setArgumentValue("compFile", componentFile);
        generator.setArgumentValue("ruleName", currentSelectedRule.getName());
        generator.setArgumentValue("ruleFile",  currentSelectedRule.getRuleFile());
        generator.setArgumentValue("goldenSyntaxFile", goldenSyntaxFile);
        
        try {
            File f = new File(testPath + "Test" + componentName + "_" +
                    currentSelectedRule.toString() + ".java");
            FileOutputStream fos = new FileOutputStream(f);
            PrintStream ps = new PrintStream(fos);

            ps.print(generator.toString());

            fos.close();
        }
        catch(Exception ex) {
            System.out.println(ex);            
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    // Referente ao botao de geracao do teste do modelo do grafo
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String testPath = testPathField.getText();
        
        // Escreve o arquivo do grafo
        String goldenGraphFile = new String(componentName + "_ModelGraph.dot");
        try {
            File f = new File(testPath + goldenGraphFile);
            FileOutputStream fos = new FileOutputStream(f);
            PrintStream ps = new PrintStream(fos);

            ps.print(dotGraph);

            fos.close();
        }
        catch(Exception ex) {
            System.out.println(ex);
        }
        
        FileGenerator generator = 
                FileGeneratorParser.parse("/home/ivan/odog/odog/src/odog/test/TestComponentGraphModel.xml");
        if(isAtomic) {
            generator.setArgumentValue("isAtomic", "true");
        }
        else {
            generator.setArgumentValue("isAtomic", "false");
        }
        
        generator.setArgumentValue("compName", componentName);
        generator.setArgumentValue("compFile", componentFile);
        generator.setArgumentValue("goldenGraphFile", goldenGraphFile);
        
        try {
            File f = new File(testPath + "Test" + componentName + "GraphModel.java");
            FileOutputStream fos = new FileOutputStream(f);
            PrintStream ps = new PrintStream(fos);

            ps.print(generator.toString());

            fos.close();
        }
        catch(Exception ex) {
            System.out.println(ex);            
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    // Referente a geraco do teste para a syntaxe do ator
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String testPath = testPathField.getText();
        
        // Escreve o arquivo golden XML
        String goldenSyntaxFile = new String(componentName + "ST");
        try {
            File f = new File(testPath + goldenSyntaxFile);
            FileOutputStream fos = new FileOutputStream(f);
            PrintStream ps = new PrintStream(fos);

            ps.print(componentXML.getText());

            fos.close();
        }
        catch(Exception ex) {
            System.out.println(ex);
        }

        FileGenerator generator = 
                FileGeneratorParser.parse("/home/ivan/odog/odog/src/odog/test/TestComponentSyntax.xml");
        // Escreve o template para o teste
        if(isAtomic) {
            generator.setArgumentValue("isAtomic", "true");
        }
        else {
            generator.setArgumentValue("isAtomic", "false");
        }
        generator.setArgumentValue("compName", componentName);
        generator.setArgumentValue("compFile", componentFile);
        generator.setArgumentValue("goldenSyntaxFile", goldenSyntaxFile);

        try {
            File f = new File(testPath + "Test" + componentName + ".java");
            FileOutputStream fos = new FileOutputStream(f);
            PrintStream ps = new PrintStream(fos);

            ps.print(generator.toString());

            fos.close();
        }
        catch(Exception ex) {
            System.out.println(ex);            
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    // Esse evento eh usado para mostrar a regra selecionada
    private void ruleListMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ruleListMouseReleased
        Object obj = ruleList.getSelectedValue();
        if(obj == null) return;
        
        Rule r = (Rule) obj;
        if(r == currentSelectedRule) return;

        currentSelectedRule = r;

        setRuleText(r.getExpression());
        setRuleSyntaxTree(r.getSyntaxTree());
    }//GEN-LAST:event_ruleListMouseReleased

    // Evento para o click de uma regra
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CheckerResultsFrame().setVisible(true);
            }
        });
    }

    public void setDotGraph(String graph) {
        dotGraph = graph;        
    }
    
    public void setIsAtomic() {
        isAtomic = true;
    }
    
    public void setComponentName(String name) {
        componentName = name;
    }

    public void setComponentFile(String file) {
        componentFile = file;
    }
    
    public void setComponentXML(String text) {
        componentXML.setText(text);
    }

    public void setComponentSyntaxTree(DefaultMutableTreeNode node) {
        DefaultTreeModel model = new DefaultTreeModel(node);
        componentSyntax.setModel(model);
    }
    
    public void setRules(LinkedList rules) {
        DefaultListModel model = new DefaultListModel();
        for(int i = 0;i < rules.size();i++) {
            Rule r = (Rule) rules.get(i);
            model.add(i, r);
        }
        ruleList.setModel(model);
    }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTree componentSyntax;
    private javax.swing.JTextArea componentXML;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JList ruleList;
    private javax.swing.JTree ruleSyntaxTree;
    private javax.swing.JTextArea ruleText;
    private javax.swing.JTextField testPathField;
    // End of variables declaration//GEN-END:variables

    private Rule currentSelectedRule;

    private String componentFile;
    private String componentName;
    private String dotGraph;
    
    // Isso aqui eh ruim. Talvez eu devesse unificar o xml de atomico e topologia.
    private boolean isAtomic;
    
    private void setRuleText(String text) {
        ruleText.setText(text);
    }
    
    private void setRuleSyntaxTree(DefaultMutableTreeNode node) {
        DefaultTreeModel model = new DefaultTreeModel(node);
        ruleSyntaxTree.setModel(model);
    }
}
